package service

import (
	"bytes"
	"context"
	"encoding/json"
	"log"
	"video-srv/basic/config"
	__ "video-srv/basic/proto/rpc"
)

func (s *VideoServer) EsSearchVideoList(_ context.Context, in *__.EsSearchVideoListReq) (*__.EsSearchVideoListResp, error) {
	query := map[string]interface{}{}
	var buf bytes.Buffer
	if in.Keyword == "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"title": in.Keyword,
				},
			},
		}
	}
	if in.Page > 0 && in.Size > 0 {
		from := (in.Page - 1) * in.Size
		query["from"] = from
		query["size"] = in.Size
	}
	if in.Sort == "asc" || in.Sort == "desc" {
		query["sort"] = []map[string]interface{}{
			{
				"id": map[string]string{
					"order": in.Sort,
				},
			},
		}
	}
	if in.Keyword != "" {
		query["highlight"] = map[string]interface{}{
			"fields": map[string]interface{}{
				"title": map[string]interface{}{},
			},
		}
	}
	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}
	es := config.Es
	res, err := es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex("video_110501"),
		es.Search.WithBody(&buf),
		es.Search.WithTrackTotalHits(true),
		es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
	r := map[string]interface{}{}
	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		log.Fatalf("Error parsing the response body: %s", err)
	}
	var videoList []*__.VideoList
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		source := hit.(map[string]interface{})["_source"].(map[string]interface{})
		video := &__.VideoList{
			Id:           int64(source["id"].(float64)),
			Title:        source["title"].(string),
			Image:        source["image"].(string),
			Tags:         source["tags"].(string),
			Refer:        source["refer"].(string),
			AreaName:     source["areaName"].(string),
			CategoryName: source["categoryName"].(string),
			ChannelName:  source["channelName"].(string),
			YearName:     source["yearName"].(string),
		}
		videoList = append(videoList, video)
	}
	return &__.EsSearchVideoListResp{
		List: videoList,
	}, nil
}
